<template>
    <div>
        <div class="drawBox">
            <!-- canvas绘图 -->  
            <div class="paintBox" :style="{cursor:cursorStyle}" @click="startDraw" @contextmenu.prevent="endDraw">
                <!-- <img :src="src" alt=""> -->
                <canvas class="myCanvas" id="canvas"></canvas>
                <canvas class="myCanvas" id="loopcanvas"></canvas>
            </div> 
            
        </div>
        <div class="buttonC">
            <el-button @click="download">下载</el-button>  
            <el-button @click="clearAllLine">清除</el-button> 
            <el-button @click="saveTo3d">设置为3d</el-button>
        </div>
        <el-form class="formbox" ref="form" :model="form" label-width="80px">
            <el-form-item label="标记信息">
                        <el-input
                            v-model="form.lng">
                        </el-input>
                        <el-input
                            v-model="form.lat">
                        </el-input>
                        <el-input
                            v-model="form.deep">
                        </el-input>
            </el-form-item>
            <el-form-item label="批注信息">
                <el-input type="textarea" v-model="form.desc"></el-input>
            </el-form-item>
            <el-button @click="save" class="save" type="primary">保存批注</el-button> 
        </el-form> 
    </div>
</template>

<script>
export default {
    name: 'popup',
    props: {
        src: {},
        lineStr:{}
        },
    data() {
        return {
            isFirstClick: 0,
            dbClick: false,
            offsetXY: [],
            loopcanvas:null,
            singcanvas:null,
            dbcanvas:null,
            imgWidth:10000,
            imgHeight:10000,
            loading:true,
            drawLoop:null,
            form:{
                lng:undefined,
                lat:undefined,
                deep:undefined
            },
            cursorStyle:"crosshair",
            dataFordraw:{},//绘制的插值数据对象
            //侧线起始点坐标
            startPoint:[],
            // 侧线的距离
            lineLength:0,
            //方向
            lineDegree:0,
            //最大深度
            maxHeight:0
        };
    },
    created() {
        // debugger
    //    this.loadImg()
    },
    computed: {},
    watch:{
        src(val){
            // this.loadImg()
            if(val!=""){
                this.drawCanvas(val.data)
                    this.dataFordraw = val.data
                    this.maxHeight=val.data.maxY-val.data.minY
                }
        },
        lineStr(val){
            if(val.length==2){
                 let lng1 = parseFloat(val[0][0])
                 let lat1 = parseFloat(val[0][1])
                 let lng2 = parseFloat(val[1][0])
                 let lat2 = parseFloat(val[1][1])
                 this.startPoint=[lng1,lat1]
                this.lineLength = this.GetDistance(lat1,  lng1,  lat2,  lng2)
                this.lineDegree = this.getDegree(lat1, lng1, lat2, lng2)
                 
            }
            console.log(this.lineLength)
            console.log(this.lineDegree)
        }
    },
    methods: {
        //加载图片并设置为bg
        loadImg(){
            const _this = this
            if(this.src==""){
                let canvas1 = document.getElementById('canvas')
                if(canvas1){
                    let canvas2 =document.getElementById('loopcanvas')
                    canvas1.width = 0
                    canvas2.width = 0
                    this.imgWidth = 0
                    this.imgHeight = 0
                    canvas1.height = 0
                    canvas2.height = 0
                    canvas1.getContext('2d').clearRect(0, 0, 10000,10000)
                    canvas2.getContext('2d').clearRect(0, 0, 10000,10000)
                    return
                } 
            }
            let img_url = this.src
            console.log(img_url)
            let img = new Image()
            img.setAttribute('crossOrigin', 'anonymous');
            img.src = img_url
            // 加载完成执行
            img.onload = function(){
                let canvas1 = document.getElementById('canvas')
                let canvas2 =document.getElementById('loopcanvas')
                canvas1.width = img.width
                canvas2.width = img.width
                this.imgWidth = img.width
                this.imgHeight = img.height
                canvas1.height = img.height
                canvas2.height = img.height
                let canvasbg = canvas1.getContext("2d");
                let bg = canvasbg.createPattern(img, "no-repeat");//createPattern() 方法在指定的方向内重复指定的元素。
                canvasbg.fillStyle = bg;//fillStyle 属性设置或返回用于填充绘画的颜色、渐变或模式。
                canvasbg.fillRect(0, 0, canvas1.width, canvas1.height);//绘制已填充矩形fillRect(左上角x坐标, 左上角y坐标, 宽, 高)
                setTimeout(() => { 
                _this.loading=false},500)
            }
        },
        // 在三视图上画异常
		startDraw(e) {
                const _this = this
                this.isFirstClick++
                console.log(this.isFirstClick)
                this.dbClick = false
                // timer = setTimeout(() => { // 单击还是双击
                // 	if(this.dbClick === true) {
                        let xy = {
                            x: e.offsetX,
                            y: e.offsetY
                        }
                        this.offsetXY.push(xy)
                        console.log('单击取点', this.offsetXY )
                        if(this.offsetXY.length > 1) {
                            this.singcanvas = document.getElementById('canvas')
                            const singctx = this.singcanvas.getContext('2d')
                            singctx.beginPath()
                            singctx.strokeStyle = '#ED1C24'
                            singctx.moveTo(this.offsetXY[this.offsetXY.length-2].x, this.offsetXY[this.offsetXY.length-2].y)
                            singctx.lineTo(this.offsetXY[this.offsetXY.length-1].x, this.offsetXY[this.offsetXY.length-1].y)
                            singctx.stroke()
                        }
                        if(this.isFirstClick === 1) {
                            console.log('d', this.isFirstClick)
                            _this.drawLoop = _this.addOrDelEventListener(document.getElementById('loopcanvas'), 'mousemove', (e) => {
                                let xy = {
                                    x: e.offsetX,
                                    y: e.offsetY
                                }
                         
                                // console.log('重复', xy)
                                if(this.loopcanvas) {
                                    this.loopcanvas.getContext('2d').clearRect(0, 0,this.imgWidth,this.imgHeight)
                                }
                                this.loopcanvas = document.getElementById('loopcanvas')
                                const loopctx = this.loopcanvas.getContext('2d')
                                loopctx.strokeStyle = '#ED1C24'
                                loopctx.beginPath()
                                loopctx.moveTo(this.offsetXY[this.offsetXY.length-1].x, this.offsetXY[this.offsetXY.length-1].y)
                                loopctx.lineTo(xy.x, xy.y)
                                loopctx.stroke()
                            })
                        }
					// 	}
					// }, 300)
			},
			// 结束画图
			endDraw(evt) {
				// console.log('右键了', evt)
					const _this = this
					this.dbClick = false
					let xy = {
							x: evt.offsetX,
							y: evt.offsetY
					}
					this.offsetXY.push(xy)
					// this.singcanvas.getContext('2d').clearRect(0, 0, 1098, 928)
					// console.log('右键画图', this.offsetXY)
					// this.$store.state.offsetXY = this.offsetXY
					this.getExceptionLocation(this.offsetXY)
					document.getElementById("loopcanvas").removeEventListener('mousemove', _this.drawLoop())
					this.dbcanvas = document.getElementById('canvas')
					const dbctx = this.dbcanvas.getContext('2d')
					dbctx.beginPath()
					dbctx.strokeStyle = '#ED1C24'
					for(let i = 0; i < this.offsetXY.length; i++) {
						dbctx.lineTo(this.offsetXY[i].x, this.offsetXY[i].y)
					}
					dbctx.closePath()
					dbctx.stroke()
					this.isFirstClick = 0
					this.offsetXY = []
				
			},
        	// 获取异常坐标
			getExceptionLocation(offsetXY) {
				let maxY=0,minY=1000000,maxX=0,minX=1000000
				for(let xy of offsetXY) {
                    if(xy.x>maxX)maxX=xy.x
                    if(xy.x<minX)minX=xy.x
                    if(xy.y>maxY)maxY=xy.y
                    if(xy.y<minY)minY=xy.y
					// picStr += xy.x + ' ' + xy.y + ','
				}
                let abHeight = ((maxY-minY)/2+minY)/this.imgHeight  //点位图片的相对高度（对应坐标距离）
                let abWidth = ((maxX-minX)/2+(this.imgWidth - maxX))/this.imgWidth //点位图片的相对宽度（对应值的深度）
                // 距离
                let distance = abHeight*this.lineLength
                //深度
                let deep = abWidth*this.maxHeight
                let aPoint = this.computerThatLonLat(this.startPoint[0],this.startPoint[1],this.lineDegree,distance)
                this.form.lng =aPoint[0]
                this.form.lat =aPoint[1]
                this.form.deep = deep
				console.log(aPoint)
                console.log(deep)
                // console.log(maxX)
                // console.log(minX)
			},
	
            //添加删除监听方法 这个方法可以删除匿名函数监听
            addOrDelEventListener(element, type, handler, capture) {
                element.addEventListener(type, handler, capture)
                return () => {
                    element.removeEventListener(type, handler, capture)
                }
            },
            //清仓已绘制的线
            clearAllLine(){
                if(this.drawLoop!=null&&this.singcanvas!=null){
                    let loopcanvasBox= document.getElementById("loopcanvas")
                    loopcanvasBox.getContext('2d').clearRect(0, 0, this.imgWidth,this.imgHeight)
                    loopcanvasBox.removeEventListener('mousemove', this.drawLoop())
                    this.singcanvas.getContext('2d').clearRect(0, 0, this.imgWidth,this.imgHeight)
                    // this.loadImg()
                    this.drawCanvas(this.dataFordraw)
                }
            },
            //保存图片
            download(){
                // debugger
                //创建一个a标签
                let link = document.createElement('a');
                let canvas = document.getElementById('canvas')
                // canvas.toDataURL()函数执行时 返回结果是base64位的字符串 这些字符串的结果就是一张图片
                //把a标签的href属性赋值到canvas图片的地址
                link.href = canvas.toDataURL();
                // 通过a标签的download属性修改下载图片的名字
                link.download = 'canvas.png';
                //让a标签的click函数，直接下载图片
                link.click();//这句代码的作用就是相当于手动点击a标签
            },
            // 上传批注信息
            save(){

            },
            //设置为3d图
            saveTo3d(){
                
            },
            //绘制canvas
            drawCanvas(val){
                let canvas1 = document.getElementById('canvas')
                let canvas2 =document.getElementById('loopcanvas')
                canvas1.width = val.width
                canvas2.width = val.width
                this.imgWidth = val.width
                this.imgHeight = val.height
                canvas1.height = val.height
                canvas2.height = val.height
                canvas1.getContext('2d').clearRect(0, 0, this.imgWidth,this.imgHeight)
                canvas1.style.display = 'block';
                //设置canvas透明度
                canvas1.getContext('2d').globalAlpha =1;
                let extent = [val.minX,val.minY,val.maxX,val.maxY]
                let zlim=[val.minZ,val.maxZ]
                let colors= ["#000080", "#0001FF",  "#0054FF", "#00A8FF", "#16FFE1", "#5AFF9D", "#9DFF5A", "#E4FF13", "#FFBD00", "#FF2200", "#AD0000", "#800000"]
                let data= val.data
                //使用分层设色渲染
                this.plot(canvas, data,
                    [extent[0], extent[2]], [extent[1], extent[3]],zlim,colors); 
            },
            //将插值数据汇入canvas
            plot(canvas, grid, xlim, ylim, zlim,colors) {
                // Clear screen
                var ctx = canvas.getContext("2d");
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                // Starting boundaries
                var i, j, x, y, z;
                var n = grid.length;
                var m = grid[0].length;
                var wx = (canvas.width/n);
                var wy = (canvas.height/m);

                for(i=0;i<n;i++){
                        for(j=0;j<m;j++) {
                        if(grid[i][j]==undefined) continue;
                        z = grid[i][j];
                        let a= (grid[i][j]-zlim[0])/(zlim[1]-zlim[0]);
                        if(a<0.0) a = 0.0;
                        if(a>1.0) a = 1.0;
                        
                        ctx.fillStyle = colors[Math.floor((colors.length-1)*a)];
                        ctx.fillRect(i*wx,j*wy,wx,wy);
                        }
                        
                    }
                },
            // 通过两点坐标计算距离 方法定义 lat,lng
            GetDistance( lat1,  lng1,  lat2,  lng2){
                var radLat1 = lat1*Math.PI / 180.0;
                var radLat2 = lat2*Math.PI / 180.0;
                var a = radLat1 - radLat2;
                var  b = lng1*Math.PI / 180.0 - lng2*Math.PI / 180.0;
                var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
                Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
                s = s *6378.137 ;// EARTH_RADIUS;
                s = Math.round(s * 10000) / 10000;
                return s*1000;
            },
            //计算角度 北方向顺时针
            getDegree(latA, lonA, latB, lonB){
                let radLatA = latA* Math.PI / 180.0;
                let radLonA = lonA* Math.PI / 180.0;
                let radLatB = latB* Math.PI / 180.0;
                let radLonB = lonB* Math.PI / 180.0;
                let dLon = radLonB - radLonA
                let y = Math.sin(dLon) * Math.cos(radLatB)
                let x = Math.cos(radLatA) * Math.sin(radLatB) - Math.sin(radLatA) * Math.cos(radLatB) * Math.cos(dLon)
                let brng = Math.atan2(y, x)* 180.0 / Math.PI;
                brng = (brng + 360.0) % 360.0
                // brng = brng.toFixed(2)
                return brng
            },
            //通过距离、角度、坐标点计算另一个坐标位置
	        computerThatLonLat(lon,lat,brng,dist){
            	/** 长半径a=6378137 */
                var a = 6378137;
                /** 短半径b=6356752.3142 */
                var b = 6356752.3142;
                /** 扁率f=1/298.2572236 */
                var f = 1 / 298.2572236;
				var brng1 = brng
				if(brng<0){
					brng1 = (brng+360.0)
				}
				var alpha1 = brng1* Math.PI / 180.0;
				var sinAlpha1 = Math.sin(alpha1);
				var cosAlpha1 = Math.cos(alpha1);
				var tanU1 = (1 - f) * Math.tan(lat* Math.PI / 180.0);
				var cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1));
				var sinU1 = tanU1 * cosU1;
				var sigma1 = Math.atan2(tanU1, cosAlpha1);
				var sinAlpha = cosU1 * sinAlpha1;
				var cosSqAlpha = 1 - sinAlpha * sinAlpha;
				var uSq = cosSqAlpha * (a * a - b * b) / (b * b);
				var A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
				var B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
				var cos2SigmaM=0;
				var sinSigma=0;
				var cosSigma=0;
				var sigma = dist / (b * A), sigmaP = 2 * Math.PI;
				while (Math.abs(sigma - sigmaP) > 1e-12) {
					cos2SigmaM = Math.cos(2 * sigma1 + sigma);
					sinSigma = Math.sin(sigma);
					cosSigma = Math.cos(sigma);
					var deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)
							- B / 6 * cos2SigmaM * (-3 + 4 * sinSigma * sinSigma) * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
					sigmaP = sigma;
					sigma = dist / (b * A) + deltaSigma;
				}
				var tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
				var lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1,
						(1 - f) * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
				var lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma * cosAlpha1);
				var C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
				var L = lambda - (1 - C) * f * sinAlpha
						* (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
				var revAz = Math.atan2(sinAlpha, -tmp); // final bearing
				return [lon+L* 180.0 / Math.PI,lat2* 180.0 / Math.PI]
	},
    },
};
</script>

<style scoped lang="scss">
.drawBox{
    // text-align: center;
    width: 100%;
    height: 350px;
    overflow: auto;
}
.paintBox{
    position: relative;
    display:inline-block;
    min-height: 100px;
}
.formbox{
    /* margin-top: 10px; */
    padding: 10px;
    .save{
        margin-left: 80px;
    }
}
.buttonC{
    text-align: center;
    width: 100%;
}
.myCanvas{
        transform-origin: 0 0;
        transform: rotate(-90deg) translate(-100%, 0px);
        position: absolute;
        margin-top: 10px;
        margin-left: 20px;
		}
</style>